<template>
  <div ref="divRef">
    <div class="aie-container">
      <div class="aie-container-header"></div>
      <div class="aie-container-main"></div>
      <div class="aie-container-footer"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {AiEditor} from "aieditor";
import "aieditor/dist/style.css"
import {onMounted, onUnmounted, ref, watch} from "vue";
import {getToken} from "@/utils/auth";

const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: String,
  },
  placeholder: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

const baseUrl = import.meta.env.VITE_API_BASE_URL;
const token = getToken();

const content = ref(props.modelValue)
const placeholder = ref(props.placeholder)
const disabled = ref(props.disabled)
const watchContent = ref('');

const divRef = ref();
let aiEditor: AiEditor | null = null;

onMounted(() => {
  // @ts-ignore
  aiEditor = new AiEditor({
    element: divRef.value as Element,
    placeholder: placeholder.value,
    content: content.value,
    toolbarKeys: ["undo", "redo", "brush", "eraser",
      "|", "heading", "font-family", "font-size",
      "|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript", "hr", "todo", "emoji",
      "|", "highlight", "font-color",
      "|", "align", "line-height",
      "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
      "|", "image", "video", "attachment", "quote", "code-block", "table",
      "|", "printer", "fullscreen"
    ],
    onChange:(aiEditor)=>{
      // 监听到用编辑器内容发生变化了，控制台打印编辑器的 html 内容...
      //console.log(aiEditor.getHtml())
      emit("update:modelValue", aiEditor.getHtml());
    },
    uploader: (file, uploadUrl, headers, formName) => {
      //可自定义上传逻辑
      const formData = new FormData();
      formName = 'file';
      formData.append(formName, file);
      return new Promise((resolve, reject) => {
        fetch(uploadUrl, {
          method: "post",
          headers: {'Accept': 'application/json', ...headers},
          body: formData,
        }).then((resp) => resp.json())
            .then(json => {
              resolve(json);
            }).catch((error) => {
          reject(error);
        })
      });
    },
    image: {
      allowBase64: true,
      defaultSize: 350,
      uploadUrl: `${baseUrl}/file/upload`,
      uploadHeaders: {
        "Authorization": `Bearer ${token}`,
      },
      uploaderEvent: {
        onUploadBefore: (file, uploadUrl, headers) => {
          //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
        },
        onSuccess: (file, response) => {
          //监听图片上传成功
          //注意：
          // 1、如果此方法返回 false，则图片不会被插入到编辑器
          // 2、可以在这里返回一个新的 json 给编辑器
          if (response.code === 200) {
            return {
              "errorCode": 0,
              "data": {
                "src": baseUrl + response.data,
                "alt": ""
              }
            }
          }
        },
        onFailed: (file, response) => {
          //监听图片上传失败，或者返回的 json 信息不正确
        },
        onError: (file, error) => {
          //监听图片上传错误，比如网络超时等
        },
      }
    },
    video: {
      uploadUrl: `${baseUrl}/file/upload`,
      uploadHeaders: {
        "Authorization": `Bearer ${token}`,
      },
      uploaderEvent: {
        onUploadBefore: (file, uploadUrl, headers) => {
          //监听视频上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
        },
        onSuccess: (file, response) => {
          //监听视频上传成功
          //注意：
          // 1、如果此方法返回 false，则视频不会被插入到编辑器
          // 2、可以在这里返回一个新的 json 给编辑器
          if (response.code === 200) {
            return {
              "errorCode": 0,
              "data": {
                // 视频播放地址
                "src": baseUrl + response.data,
                // 视频
                "poster": ""
              }
            }
          }
        },
        onFailed: (file, response) => {
          //监听视频上传失败，或者返回的 json 信息不正确
        },
        onError: (file, error) => {
          //监听视频上传错误，比如网络超时等
        },
      }
    },
    attachment: {
      uploadUrl: `${baseUrl}/file/upload`,
      uploadHeaders: {
        "Authorization": `Bearer ${token}`,
      },
      uploaderEvent: {
        onUploadBefore: (file, uploadUrl, headers) => {
          //监听附件上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
        },
        onSuccess: (file, response) => {
          //监听附件上传成功
          //注意：
          // 1、如果此方法返回 false，则附件不会被插入到编辑器
          // 2、可以在这里返回一个新的 json 给编辑器
          if (response.code === 200) {
            return {
              "errorCode": 0,
              "data": {
                "href": baseUrl + response.data,
                "fileName": file.name
              }
            }
          }
        },
        onFailed: (file, response) => {
          //监听附件上传失败，或者返回的 json 信息不正确
        },
        onError: (file, error) => {
          //监听附件上传错误，比如网络超时等
        },
      }
    }
  })
})

onUnmounted(() => {
  aiEditor && aiEditor.destroy();
})

watch(
    () => props.modelValue,
    (newVal:string) => {
      if (aiEditor?.getHtml() !== newVal) {
        aiEditor?.setContent(newVal);
      }

    },
    { deep: true }
);
</script>

<style scoped lang="less">
.aie-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--aie-bg-color);
}

.aie-container-main {
  flex-grow: 1;
  overflow: auto;
}

.aie-container-footer {
  display: none;
}
</style>
